# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from odoo import models, fields, api
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare
from odoo.osv import orm
from odoo.tools.translate import _
from odoo.exceptions import ValidationError


class StockReturnPickingLine(models.TransientModel):
    _inherit = "stock.return.picking.line"

    origin_quantity = fields.Float(u"可以退回的数量", digits=dp.get_precision('Product Unit of Measure'))

    @api.constrains("quantity")
    def _check_quantity(self):
        for line in self:
            if line.quantity > line.origin_quantity:
                raise ValidationError(u"退回数量不能超出原单据可以退回的数量。")


class StockReturnPicking(models.TransientModel):
    _inherit = "stock.return.picking"

    return_reason = fields.Char(u'退货原因')

    @api.model
    def default_get(self, field_names):
        res = super(StockReturnPicking, self).default_get(field_names)
        if res.get('product_return_moves'):
            for return_move in res['product_return_moves']:
                val = return_move[2]
                val.update({"origin_quantity": val["quantity"]})
        return res

    @api.multi
    def _create_returns(self):
        new_picking_id, pick_type_id = super(StockReturnPicking, self)._create_returns()
        new_picking = self.env['stock.picking'].browse([new_picking_id])
        if new_picking and self.return_reason:
            new_picking.return_reason=self.return_reason
        return new_picking_id, pick_type_id

class StockPicking(models.Model):
    _inherit = 'stock.picking'

    return_reason = fields.Char(u'退货原因')
    enable_return = fields.Boolean(related="picking_type_id.enable_return", readonly=True)
